package com.lost.octopus.es.helper.builder;

import com.lost.octopus.es.helper.constant.EsMatchMode;
import com.lost.octopus.es.helper.constant.EsMatchType;
import com.lost.octopus.es.helper.entity.model.FieldConfig;

import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

import lombok.extern.log4j.Log4j2;

/**
 * 字段匹配构建工具
 * @author zhangbh
 **/
@Log4j2
public class FieldMatchBuilders {

    /**
     * 内置匹配规则
     * @param config 查询配置
     * @return 查询Builder对象
     */
    public QueryBuilder useBuilder(FieldConfig config) {
        String fieldName = config.getName();
        EsMatchMode mode = config.getMatchMode();
        // 构建查询方式
        log.debug("字段相等类型={}", config.getMatchType());
        // 默认全等
        switch (config.getMatchType()) {
            case prefix:
                return QueryBuilders.prefixQuery(fieldName, String.valueOf(config.getValue()));
            case wildcard:
                // 匹配模式
                String wildcardStr = "*%s*";
                if (mode.equals(EsMatchMode.wildcard_left)) {
                    wildcardStr = "*%s";
                } else if (mode.equals(EsMatchMode.wildcard_right)) {
                    wildcardStr = "%s*";
                }
                return QueryBuilders.wildcardQuery(fieldName, String.format(wildcardStr, config.getValue()));
            case match:
                return QueryBuilders.matchQuery(fieldName, config.getValue());
            case fuzzy:
                return QueryBuilders.fuzzyQuery(fieldName, config.getValue());
            case regexp:
                return QueryBuilders.regexpQuery(fieldName, (String) config.getValue());
            default:
                return QueryBuilders.termQuery(fieldName, config.getValue());
        }
    }
}
